<template>
  <div
    class="plot-style-panel"
    v-if="visible"
    :style="{ left: position.x + 'px', top: position.y + 'px' }"
    ref="plotStylePanel"
  >
    <div
      class="panel-header"
      @mousedown="startDrag"
    >
      <span class="panel-title">属性编辑</span>
      <i class="el-icon-close" @click="handleClose"></i>
    </div>

    <div class="panel-content">
      <!-- 属性类型切换 -->
      <div class="style-type-switch">
        <span
          v-for="(item, index) in plotStyleBtn"
          :key="index"
          :class="[plotActive === index ? 'active' : '']"
          @click="onChangePlotStyle(index)"
        >
          {{ item }}
        </span>
      </div>

      <!-- 标绘属性 -->
      <div v-if="plotActive && Object.keys(plotStyleAttr).length">
        <div
          class="plot-type"
          v-for="(item, index) in plotStyleAttr"
          :key="index"
        >
          <!-- 复选框类型 -->
          <template v-if="item.type === 'checkbox'">
            <el-row class="attr-row">
              <el-col :span="8" class="attr-label">{{ item.name }}：</el-col>
              <el-col :span="16">
                <el-radio-group
                  v-model="item.value"
                  @change="handleStyleChange"
                >
                  <el-radio
                    v-for="(opt, index) in item.options"
                    :key="index"
                    :label="index"
                  >
                    {{ opt.name }}
                  </el-radio>
                </el-radio-group>
              </el-col>
            </el-row>

            <!-- 子选项 -->
            <template v-for="(opt, key) in item.options">
              <template v-if="key === item.value">
                <template v-for="(detail, detailKey) in opt">
                  <Detail
                    v-if="detailKey !== 'name' && detailKey !== 'value'"
                    :key="detailKey"
                    :detailAttr="detail"
                    @toChange="handleStyleChange"
                  >
                    <el-col :span="8" class="attr-label"
                      >{{ detail.name }}：</el-col
                    >
                  </Detail>
                </template>
              </template>
            </template>
          </template>

          <!-- 普通属性 -->
          <template v-else>
            <Detail :detailAttr="item" @toChange="handleStyleChange">
              <el-col :span="8" class="attr-label">{{ item.name }}：</el-col>
            </Detail>
          </template>
        </div>
      </div>

      <!-- 自有属性 -->
      <div v-if="!plotActive">
        <div class="attr-row" v-for="(item, index) in infos" :key="index">
          <el-col :span="8" class="attr-label">{{ item.fieldName }}：</el-col>
          <el-col :span="16">
            <el-input
              v-model="item.value"
              :placeholder="'请输入' + item.fieldName"
              @change="handleAttrChange"
            ></el-input>
          </el-col>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import plotStyle from "./plotStyle.js";
import Detail from "@/views/map3d/components/detail/Detail.vue";

export default {
  name: "PlotStyle",
  components: {
    Detail,
  },
  data() {
    return {
      visible: false,
      plotStyleBtn: ["自有属性", "标绘属性"],
      plotActive: 1,
      plotStyleAttr: {},
      infos: [
        {
          fieldName: "名称",
          value: "",
        },
        {
          fieldName: "备注",
          value: "",
        },
      ],
      currentEntity: null,
      position: {
        x: window.innerWidth - 380,
        y: 50
      },
      isDragging: false,
      dragOffset: {
        x: 0,
        y: 0
      }
    };
  },
  mounted() {
    window.addEventListener('resize', this.updatePosition);
    document.addEventListener('mousemove', this.onDrag);
    document.addEventListener('mouseup', this.stopDrag);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.updatePosition);
    document.removeEventListener('mousemove', this.onDrag);
    document.removeEventListener('mouseup', this.stopDrag);
  },
  methods: {
    updatePosition() {
      if (!this.isDragging) {
        this.position.x = window.innerWidth - 380;
      }
    },
    open(entity) {
      console.log("Opening plot style panel with entity:", entity);
      this.visible = true;
      this.position.x = window.innerWidth - 380;
      this.currentEntity = entity;
      if (entity) {
        this.setAttr(entity);
      }
    },
    handleClose() {
      this.visible = false;
      this.currentEntity = null;
      this.plotStyleAttr = {};
    },
    onChangePlotStyle(index) {
      this.plotActive = index;
    },
    setAttr(entity) {
      if (!entity) {
        console.warn("Invalid entity");
        return;
      }

      // 设置自有属性
      const entityAttr = entity.getAttr ? entity.getAttr() : {};
      if (entityAttr) {
        this.infos = entityAttr;
      }

      // 获取样式类型
      let styleType;
      if (entity.attr && entity.attr.styleType) {
        styleType = entity.attr.styleType;
      } else if (entity.type) {
        // 根据实体类型映射到对应的样式类型
        switch (entity.type.toLowerCase()) {
          case "polygon":
            styleType = "polygon";
            break;
          case "polyline":
            styleType = "polyline";
            break;
          case "point":
            styleType = "point";
            break;
          case "billboard":
            styleType = "billboard";
            break;
          case "label":
            styleType = "label";
            break;
          default:
            styleType = entity.type.toLowerCase();
        }
      }

      console.log("Style type:", styleType);

      if (!plotStyle[styleType]) {
        console.warn("未找到对应的标绘样式配置:", styleType);
        return;
      }

      // 深拷贝样式配置
      this.plotStyleAttr = JSON.parse(JSON.stringify(plotStyle[styleType]));
      console.log("Plot style attributes:", this.plotStyleAttr);

      // 获取当前样式
      const entityStyle = entity.getStyle
        ? entity.getStyle()
        : entity.style || {};
      console.log("Entity style:", entityStyle);

      // 设置当前样式值
      for (let key in this.plotStyleAttr) {
        let attr = this.plotStyleAttr[key];

        if (attr.type === "checkbox") {
          // 处理复选框类型
          if (typeof entityStyle[key] === "boolean") {
            attr.value = entityStyle[key] ? "show" : "hide";
          } else {
            attr.value = entityStyle[key] || attr.value;
          }

          // 设置子选项的值
          const selectedOption = attr.options[attr.value];
          if (selectedOption) {
            for (let optKey in selectedOption) {
              if (optKey !== "name" && optKey !== "value") {
                const optionValue = entityStyle[optKey];
                if (optionValue !== undefined) {
                  selectedOption[optKey].value = optionValue;
                }
              }
            }
          }
        } else {
          // 处理普通属性
          const styleValue = entityStyle[key];
          if (styleValue !== undefined) {
            attr.value = styleValue;
          }
        }
      }

      // 更新实体属性
      if (entity.setAttr) {
        entity.setAttr(this.infos);
      }
    },
    handleStyleChange() {
      if (!this.currentEntity) return;

      const style = this.transformStyleVal(this.plotStyleAttr);
      console.log("Updated style:", style);

      if (window.plotDrawTool) {
        window.plotDrawTool.updateOneStyle(this.currentEntity, style);
      }
    },
    handleAttrChange() {
      if (!this.currentEntity) return;
      if (this.currentEntity.setAttr) {
        this.currentEntity.setAttr(this.infos);
      }
    },
    transformStyleVal(style) {
      if (!style) return {};
      const styleVal = {};

      for (let key in style) {
        const item = style[key];

        if (item.type === "checkbox") {
          const option = item.options[item.value];
          if (!option) continue;

          // 设置主属性值
          styleVal[key] = option.value;

          // 设置子选项值
          for (let optKey in option) {
            if (optKey !== "name" && optKey !== "value") {
              styleVal[optKey] = option[optKey].value;
            }
          }
        } else {
          // 处理普通属性
          styleVal[key] = item.value;
        }
      }

      return styleVal;
    },
    startDrag(e) {
      if (e.target.className === 'el-icon-close') return;

      this.isDragging = true;
      const rect = this.$refs.plotStylePanel.getBoundingClientRect();
      this.dragOffset = {
        x: e.clientX - rect.left,
        y: e.clientY - rect.top
      };
    },
    onDrag(e) {
      if (!this.isDragging) return;

      // 计算新位置
      let newX = e.clientX - this.dragOffset.x;
      let newY = e.clientY - this.dragOffset.y;

      // 获取窗口尺寸
      const windowWidth = window.innerWidth;
      const windowHeight = window.innerHeight;

      // 获取面板尺寸
      const panelRect = this.$refs.plotStylePanel.getBoundingClientRect();
      const panelWidth = panelRect.width;
      const panelHeight = panelRect.height;

      // 限制面板不超出窗口范围
      newX = Math.max(0, Math.min(newX, windowWidth - panelWidth));
      newY = Math.max(0, Math.min(newY, windowHeight - panelHeight));

      this.position = {
        x: newX,
        y: newY
      };
    },
    stopDrag() {
      this.isDragging = false;
    }
  },
};
</script>

<style lang="scss" scoped>
.plot-style-panel {
  position: fixed;
  background: #fff;
  border-radius: 4px;
  color: #333;
  z-index: 1000;
  width: 360px;
  user-select: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

  .panel-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px 15px;
    border-bottom: 1px solid #dcdfe6;
    cursor: move;
    background-color: #f5f7fa;

    .panel-title {
      font-size: 14px;
      font-weight: 700;
      color: #303133;
    }

    i {
      cursor: pointer;
      font-size: 16px;
      color: #909399;

      &:hover {
        color: #409EFF;
      }
    }
  }

  .panel-content {
    padding: 10px;
    max-height: calc(100vh - 200px);
    overflow-y: auto;
    background-color: #fff;
    color: #333;

    .style-type-switch {
      display: flex;
      margin-bottom: 15px;

      span {
        flex: 1;
        text-align: center;
        padding: 8px;
        cursor: pointer;
        border: 1px solid #dcdfe6;
        transition: all 0.3s;
        color: #606266;

        &:first-child {
          border-radius: 4px 0 0 4px;
        }

        &:last-child {
          border-radius: 0 4px 4px 0;
        }

        &.active {
          background: #409eff;
          border-color: #409eff;
          color: #fff;
        }

        &:hover:not(.active) {
          border-color: #409eff;
          color: #409eff;
        }
      }
    }

    .attr-row {
      margin-bottom: 15px;
      display: flex;
      align-items: center;

      .attr-label {
        text-align: right;
        padding-right: 12px;
        color: #606266;
      }
    }

    .plot-type {
      margin-bottom: 20px;

      &:last-child {
        margin-bottom: 0;
      }
    }
  }
}

:deep(.el-radio) {
  margin-right: 15px;
  .el-radio__label {
    color: #606266;
  }
}

:deep(.el-input__inner) {
  background-color: #fff;
  border: 1px solid #dcdfe6;
  color: #606266;
}

:deep(.el-slider__runway) {
  background-color: #e4e7ed;
}

:deep(.el-input-number__decrease),
:deep(.el-input-number__increase) {
  background-color: #f5f7fa;
  border-color: #dcdfe6;
  color: #606266;
}

:deep(.vxe-modal--wrapper) {
  justify-content: flex-end !important;
}

:deep(.vxe-modal--box) {
  background: #fff;
}

:deep(.vxe-modal--title) {
  color: #303133;
}

:deep(.vxe-modal--header) {
  background-color: #fff;
  border-bottom: 1px solid #dcdfe6;
}

:deep(.vxe-modal--body) {
  background-color: #fff;
}

:deep(.el-radio__input.is-checked + .el-radio__label) {
  color: #409eff;
}

:deep(.el-radio__input.is-checked .el-radio__inner) {
  border-color: #409eff;
  background: #409eff;
}

:deep(.el-slider__bar) {
  background-color: #409eff;
}

:deep(.el-slider__button) {
  border-color: #409eff;
}

:deep(.el-input-number__decrease:hover),
:deep(.el-input-number__increase:hover) {
  color: #409eff;
}

:deep(.el-input.is-active .el-input__inner),
:deep(.el-input__inner:focus) {
  border-color: #409eff;
}
</style>
